﻿import QtQuick 2.0
import QtQml.Models 2.1
import QtQuick.Controls 1.4

Item {
    width: 600
    height: 800
    Rectangle {
        id:modelRect
        anchors.fill: parent
        anchors.margins: 40
        anchors.rightMargin: 100
        anchors.topMargin: 100
        border.color: "red"
        ObjectModel {
            id: itemModel
        }
        ListView {
            id:view
            anchors.fill: parent
            model: itemModel
            orientation: Qt.Vertical
            interactive: false
        }
    }
    Row{
        anchors.margins: 20
        anchors.top: parent.top
        anchors.left: parent.left
        anchors.right:  parent.right
        Repeater{
            id:rpId
            model: ["插件0","插件1","插件2","插件3","插件4","插件5"]
            Button{
                id:btn
                width: 60
                height: 30
                text: modelData
                onClicked: {
                    console.log("===data===",index);
                    var getObj = findObjetByIndex(index);
                    if( getObj == null ){
                        itemModel.append(createObject(index));
                    }else{
                        var idx = findIndexByObj(getObj);
                        itemModel.remove(idx);
                        getObj.destroy(1);
                        getObj = null;
                    }
                }
            }
        }
    }
    function createObject(index) {
        var component = Qt.createComponent("OnlyForTest.qml");
        if (component.status == Component.Ready) {
            var object = component.createObject(view);
            if(view.orientation == Qt.Horizontal){
                object.width = view.width/rpId.count
                object.anchors.top = view.top
                object.anchors.bottom = view.bottom
            }else{
//                object.width = view.width
                object.height =view.height/rpId.count
                object.anchors.left = view.left
                object.anchors.right = view.right
            }
            object.setText(index);
            console.log("object: ",object);
            return object;
        }else{
            console.log("error ");
        }
        return null;
    }

    function findIndexByObj(obj){
        for(var i= 0;i<itemModel.count;i++){
            var fdobj = itemModel.get(i);
            if(fdobj == obj){
                return i;
            }
        }
        return -1;
    }
    function findObjetByIndex(idx){
        for(var i= 0;i<itemModel.count;i++){
            var fdobj = itemModel.get(i);
            if(fdobj.getText() == idx){
                return fdobj;
            }
        }
        return null;
    }
}
